use criterion::{black_box, criterion_group, criterion_main, Criterion, BenchmarkId};
use cdb::storage::page::{PageManager, PageType};
use cdb::storage::tuple::{Tuple, DataPageManager};

/// 基准测试：页面管理器性能
fn benchmark_page_manager(c: &mut Criterion) {
    let page_manager = PageManager::new(1000);
    
    // 页面分配性能
    c.bench_function("page_allocation", |b| {
        b.iter(|| {
            let page_id = page_manager.allocate_page(PageType::Data).unwrap();
            black_box(page_id);
        })
    });
    
    // 页面读取性能
    c.bench_function("page_read", |b| {
        // 预先分配一些页面
        let page_ids: Vec<_> = (0..100)
            .map(|_| page_manager.allocate_page(PageType::Data).unwrap())
            .collect();
        
        b.iter(|| {
            let page_id = page_ids[black_box(0)];
            let page = page_manager.read_page(page_id).unwrap();
            black_box(page);
        })
    });
    
    // 页面写入性能
    c.bench_function("page_write", |b| {
        let page_id = page_manager.allocate_page(PageType::Data).unwrap();
        let page = page_manager.read_page(page_id).unwrap();
        
        b.iter(|| {
            page_manager.write_page(page.clone()).unwrap();
        })
    });
    
    // 缓存命中率测试
    c.bench_function("cache_hit_rate", |b| {
        // 预先分配页面并访问以填充缓存
        let page_ids: Vec<_> = (0..50)
            .map(|_| page_manager.allocate_page(PageType::Data).unwrap())
            .collect();
        
        // 预热缓存
        for &page_id in &page_ids {
            let _ = page_manager.read_page(page_id);
        }
        
        b.iter(|| {
            // 随机访问已缓存的页面
            let page_id = page_ids[black_box(0) % page_ids.len()];
            let page = page_manager.read_page(page_id).unwrap();
            black_box(page);
        })
    });
}

/// 基准测试：元组存储性能
fn benchmark_tuple_storage(c: &mut Criterion) {
    let page_manager = PageManager::new(1000);
    let mut data_page_manager = DataPageManager::new();
    
    // 元组插入性能
    c.bench_function("tuple_insertion", |b| {
        let page_id = page_manager.allocate_page(PageType::Data).unwrap();
        let mut page = page_manager.read_page(page_id).unwrap();
        let page_mut = std::sync::Arc::get_mut(&mut page).unwrap();
        
        b.iter(|| {
            let mut tuple = Tuple::new(3, 100);
            tuple.add_column_data(b"test_data_12345");
            
            // 注意：这里会因为空间不足而失败，但我们只测量插入性能
            let _ = data_page_manager.insert_tuple(page_mut, &tuple);
        })
    });
    
    // 元组序列化性能
    c.bench_function("tuple_serialization", |b| {
        let mut tuple = Tuple::new(5, 100);
        tuple.add_column_data(b"column1_data");
        tuple.add_column_data(b"column2_data");
        tuple.add_column_data(b"column3_data");
        tuple.set_null(1).unwrap();
        
        b.iter(|| {
            let bytes = tuple.to_bytes();
            black_box(bytes);
        })
    });
    
    // 元组反序列化性能
    c.bench_function("tuple_deserialization", |b| {
        let mut tuple = Tuple::new(5, 100);
        tuple.add_column_data(b"column1_data");
        tuple.add_column_data(b"column2_data");
        tuple.add_column_data(b"column3_data");
        tuple.set_null(1).unwrap();
        
        let bytes = tuple.to_bytes();
        
        b.iter(|| {
            let deserialized = Tuple::from_bytes(&bytes).unwrap();
            black_box(deserialized);
        })
    });
}

/// 基准测试：MVCC可见性检查性能
fn benchmark_mvcc_visibility(c: &mut Criterion) {
    let mut group = c.benchmark_group("mvcc_visibility");
    
    // 测试不同事务ID范围的可见性检查性能
    for transaction_count in [100, 1000, 10000].iter() {
        group.bench_with_input(
            BenchmarkId::new("visibility_check", transaction_count),
            transaction_count,
            |b, &tx_count| {
                let tuple = Tuple::new(3, 50); // 事务50创建的元组
                
                b.iter(|| {
                    // 测试不同事务ID的可见性
                    for tx_id in 0..tx_count {
                        let visible = tuple.is_visible_to_transaction(tx_id as u32);
                        black_box(visible);
                    }
                })
            },
        );
    }
    
    group.finish();
}

/// 基准测试：页面缓存性能
fn benchmark_page_cache(c: &mut Criterion) {
    let mut group = c.benchmark_group("page_cache");
    
    // 测试不同缓存大小的性能
    for cache_size in [100, 500, 1000].iter() {
        group.bench_with_input(
            BenchmarkId::new("cache_performance", cache_size),
            cache_size,
            |b, &size| {
                let page_manager = PageManager::new(size);
                
                // 预先分配页面
                let page_ids: Vec<_> = (0..size * 2)
                    .map(|_| page_manager.allocate_page(PageType::Data).unwrap())
                    .collect();
                
                b.iter(|| {
                    // 随机访问页面，测试缓存性能
                    for i in 0..100 {
                        let page_id = page_ids[i % page_ids.len()];
                        let page = page_manager.read_page(page_id).unwrap();
                        black_box(page);
                    }
                })
            },
        );
    }
    
    group.finish();
}

/// 基准测试：批量操作性能
fn benchmark_batch_operations(c: &mut Criterion) {
    let mut group = c.benchmark_group("batch_operations");
    
    // 批量页面分配
    group.bench_function("batch_page_allocation", |b| {
        b.iter(|| {
            let page_manager = PageManager::new(1000);
            let page_ids: Vec<_> = (0..100)
                .map(|_| page_manager.allocate_page(PageType::Data).unwrap())
                .collect();
            black_box(page_ids);
        })
    });
    
    // 批量脏页刷新
    group.bench_function("batch_dirty_page_flush", |b| {
        let page_manager = PageManager::new(1000);
        
        // 预先创建脏页面
        let page_ids: Vec<_> = (0..50)
            .map(|_| page_manager.allocate_page(PageType::Data).unwrap())
            .collect();
        
        for &page_id in &page_ids {
            let page = page_manager.read_page(page_id).unwrap();
            page_manager.write_page(page).unwrap();
        }
        
        b.iter(|| {
            page_manager.flush_dirty_pages().unwrap();
        })
    });
    
    group.finish();
}

/// 基准测试：内存使用效率
fn benchmark_memory_efficiency(c: &mut Criterion) {
    // 测试页面内存占用
    c.bench_function("page_memory_footprint", |b| {
        b.iter(|| {
            let page_manager = PageManager::new(1000);
            
            // 分配大量页面测试内存效率
            let page_ids: Vec<_> = (0..1000)
                .map(|_| page_manager.allocate_page(PageType::Data).unwrap())
                .collect();
            
            black_box(page_ids);
        })
    });
    
    // 测试元组内存占用
    c.bench_function("tuple_memory_footprint", |b| {
        b.iter(|| {
            let tuples: Vec<_> = (0..1000)
                .map(|i| {
                    let mut tuple = Tuple::new(5, i);
                    tuple.add_column_data(format!("data_{}", i).as_bytes());
                    tuple
                })
                .collect();
            
            black_box(tuples);
        })
    });
}

criterion_group!(
    benches,
    benchmark_page_manager,
    benchmark_tuple_storage,
    benchmark_mvcc_visibility,
    benchmark_page_cache,
    benchmark_batch_operations,
    benchmark_memory_efficiency
);
criterion_main!(benches);
